<template>
  <div class="match-result-container">
    <!-- 比赛信息头部 -->
    <el-card class="match-header-card" shadow="never">
      <div class="match-header">
        <div class="match-info">
          <h1 class="match-title">{{ match.name }}</h1>
          <p v-if="match.subtitle" class="match-subtitle">
            {{ match.subtitle }}
          </p>
          <div class="match-meta">
            <el-tag type="success" size="large">{{
              getStatusText(match.status)
            }}</el-tag>
            <span class="match-time"
              >{{ formatDateTime(match.startDate) }} -
              {{ formatDateTime(match.endDate) }}</span
            >
          </div>
        </div>
        <div class="actions">
          <el-button @click="$router.back()">
            <IconifyIconOffline icon="ep:back" class="mr-1" />
            返回
          </el-button>
          <el-button type="primary" @click="exportResults">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出结果
          </el-button>
          <el-button type="success" @click="generateCertificate">
            <IconifyIconOffline icon="ep:medal" class="mr-1" />
            生成证书
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 冠亚季军展示 -->
    <el-card class="podium-card" shadow="never">
      <template #header>
        <span class="title">获奖名单</span>
      </template>

      <div class="podium-container">
        <div class="podium">
          <!-- 亚军 -->
          <div v-if="topResults[1]" class="podium-item rank-2">
            <div class="podium-position">2</div>
            <div class="podium-content">
              <div class="team-avatar">
                <IconifyIconOffline icon="ep:trophy" />
              </div>
              <div class="team-name">{{ topResults[1].teamName }}</div>
              <div class="team-score">{{ topResults[1].score }}分</div>
              <div class="prize-info">{{ topResults[1].prize }}</div>
            </div>
          </div>

          <!-- 冠军 -->
          <div v-if="topResults[0]" class="podium-item rank-1">
            <div class="podium-position">1</div>
            <div class="podium-content">
              <div class="team-avatar champion">
                <IconifyIconOffline icon="ep:trophy" />
              </div>
              <div class="team-name">{{ topResults[0].teamName }}</div>
              <div class="team-score">{{ topResults[0].score }}分</div>
              <div class="prize-info">{{ topResults[0].prize }}</div>
            </div>
          </div>

          <!-- 季军 -->
          <div v-if="topResults[2]" class="podium-item rank-3">
            <div class="podium-position">3</div>
            <div class="podium-content">
              <div class="team-avatar">
                <IconifyIconOffline icon="ep:trophy" />
              </div>
              <div class="team-name">{{ topResults[2].teamName }}</div>
              <div class="team-score">{{ topResults[2].score }}分</div>
              <div class="prize-info">{{ topResults[2].prize }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 完整排名表 -->
    <el-card class="ranking-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">完整排名</span>
          <div class="filters">
            <el-select
              v-model="filterStage"
              placeholder="选择阶段"
              style="width: 120px"
              size="small"
            >
              <el-option label="全部" value="" />
              <el-option label="小组赛" value="group" />
              <el-option label="淘汰赛" value="knockout" />
              <el-option label="决赛" value="final" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索队伍"
              style="width: 200px"
              size="small"
              clearable
            >
              <template #prefix>
                <IconifyIconOffline icon="ep:search" />
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table :data="filteredResults" stripe>
        <el-table-column prop="ranking" label="排名" width="80" align="center">
          <template #default="{ row }">
            <div class="ranking-cell">
              <el-tag
                v-if="row.ranking <= 3"
                :type="getRankingType(row.ranking)"
                effect="dark"
              >
                {{ row.ranking }}
              </el-tag>
              <span v-else class="ranking-number">{{ row.ranking }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="teamName" label="队伍名称" min-width="150">
          <template #default="{ row }">
            <div class="team-cell">
              <div class="team-avatar-small">
                <IconifyIconOffline icon="ep:user-filled" />
              </div>
              <span class="team-name">{{ row.teamName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="captain" label="队长" width="120" />

        <el-table-column
          prop="totalScore"
          label="总分"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <span class="score-text">{{ row.totalScore }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="wins" label="胜" width="60" align="center">
          <template #default="{ row }">
            <span class="win-text">{{ row.wins }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="losses" label="负" width="60" align="center">
          <template #default="{ row }">
            <span class="loss-text">{{ row.losses }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="winRate" label="胜率" width="80" align="center">
          <template #default="{ row }">
            <span class="win-rate">{{ (row.winRate * 100).toFixed(1) }}%</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="avgScore"
          label="场均得分"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <span class="avg-score">{{ row.avgScore.toFixed(1) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="prize" label="奖项" width="150">
          <template #default="{ row }">
            <el-tag
              v-if="row.prize"
              :type="getPrizeType(row.ranking)"
              size="small"
            >
              {{ row.prize }}
            </el-tag>
            <span v-else class="no-prize">-</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="viewTeamDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="success"
              link
              size="small"
              @click="viewMatchHistory(row)"
            >
              比赛记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 比赛统计 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="stats-card" shadow="never">
          <template #header>
            <span class="title">比赛统计</span>
          </template>

          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-label">参赛队伍</div>
              <div class="stat-value">{{ matchStats.totalTeams }}支</div>
            </div>

            <div class="stat-item">
              <div class="stat-label">比赛场次</div>
              <div class="stat-value">{{ matchStats.totalMatches }}场</div>
            </div>

            <div class="stat-item">
              <div class="stat-label">总进球数</div>
              <div class="stat-value">{{ matchStats.totalGoals }}个</div>
            </div>

            <div class="stat-item">
              <div class="stat-label">平均每场得分</div>
              <div class="stat-value">
                {{ matchStats.avgScorePerMatch.toFixed(1) }}分
              </div>
            </div>

            <div class="stat-item">
              <div class="stat-label">最高单场得分</div>
              <div class="stat-value">{{ matchStats.highestScore }}分</div>
            </div>

            <div class="stat-item">
              <div class="stat-label">比赛天数</div>
              <div class="stat-value">{{ matchStats.totalDays }}天</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="chart-card" shadow="never">
          <template #header>
            <span class="title">得分分布</span>
          </template>

          <div ref="chartContainer" class="chart-container" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 精彩瞬间 -->
    <el-card class="highlights-card" shadow="never">
      <template #header>
        <span class="title">精彩瞬间</span>
      </template>

      <div class="highlights-content">
        <div
          v-for="highlight in highlights"
          :key="highlight.id"
          class="highlight-item"
        >
          <div class="highlight-time">{{ formatDateTime(highlight.time) }}</div>
          <div class="highlight-content">
            <div class="highlight-title">{{ highlight.title }}</div>
            <div class="highlight-desc">{{ highlight.description }}</div>
          </div>
          <div v-if="highlight.score" class="highlight-score">
            {{ highlight.score }}
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";
import * as echarts from "echarts";

const route = useRoute();
const router = useRouter();

// 图表容器引用
const chartContainer = ref<HTMLElement>();

// 比赛信息
const match = ref({
  id: 1,
  name: "2024年春季篮球联赛",
  subtitle: "青少年篮球比赛",
  startDate: "2024-03-15 08:00:00",
  endDate: "2024-03-25 18:00:00",
  status: "completed"
});

// 前三名结果
const topResults = ref([
  {
    ranking: 1,
    teamName: "雄鹰队",
    score: 95,
    prize: "冠军 - 奖金10000元"
  },
  {
    ranking: 2,
    teamName: "猛虎队",
    score: 88,
    prize: "亚军 - 奖金6000元"
  },
  {
    ranking: 3,
    teamName: "神鹰队",
    score: 82,
    prize: "季军 - 奖金3000元"
  }
]);

// 完整排名结果
const allResults = ref([
  {
    ranking: 1,
    teamName: "雄鹰队",
    captain: "张强",
    totalScore: 95,
    wins: 8,
    losses: 0,
    winRate: 1.0,
    avgScore: 11.9,
    prize: "冠军",
    stage: "final"
  },
  {
    ranking: 2,
    teamName: "猛虎队",
    captain: "李明",
    totalScore: 88,
    wins: 7,
    losses: 1,
    winRate: 0.875,
    avgScore: 11.0,
    prize: "亚军",
    stage: "final"
  },
  {
    ranking: 3,
    teamName: "神鹰队",
    captain: "王伟",
    totalScore: 82,
    wins: 6,
    losses: 2,
    winRate: 0.75,
    avgScore: 10.3,
    prize: "季军",
    stage: "knockout"
  },
  {
    ranking: 4,
    teamName: "闪电队",
    captain: "赵磊",
    totalScore: 76,
    wins: 5,
    losses: 3,
    winRate: 0.625,
    avgScore: 9.5,
    prize: "优秀奖",
    stage: "knockout"
  },
  {
    ranking: 5,
    teamName: "烈火队",
    captain: "孙杰",
    totalScore: 70,
    wins: 4,
    losses: 4,
    winRate: 0.5,
    avgScore: 8.8,
    prize: null,
    stage: "group"
  }
]);

// 比赛统计
const matchStats = ref({
  totalTeams: 16,
  totalMatches: 31,
  totalGoals: 1248,
  avgScorePerMatch: 40.3,
  highestScore: 125,
  totalDays: 11
});

// 精彩瞬间
const highlights = ref([
  {
    id: 1,
    time: "2024-03-25 16:45:00",
    title: "决赛最后一球",
    description: "雄鹰队在最后30秒投中关键三分球，锁定胜局",
    score: "95-88"
  },
  {
    id: 2,
    time: "2024-03-24 14:30:00",
    title: "半决赛逆转",
    description: "猛虎队在落后15分的情况下成功逆转，晋级决赛",
    score: "78-76"
  },
  {
    id: 3,
    time: "2024-03-22 10:15:00",
    description: "神鹰队队长王伟单场砍下32分，创造个人得分纪录",
    score: "89-72"
  }
]);

// 筛选条件
const filterStage = ref("");
const searchKeyword = ref("");

// 筛选后的结果
const filteredResults = computed(() => {
  let results = allResults.value;

  if (filterStage.value) {
    results = results.filter(item => item.stage === filterStage.value);
  }

  if (searchKeyword.value) {
    results = results.filter(
      item =>
        item.teamName
          .toLowerCase()
          .includes(searchKeyword.value.toLowerCase()) ||
        item.captain.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }

  return results;
});

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm");
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "未开始",
    ongoing: "进行中",
    completed: "已结束",
    cancelled: "已取消"
  };
  return statusMap[status] || "未知";
};

// 获取排名类型
const getRankingType = (ranking: number) => {
  if (ranking === 1) return "warning"; // 金色
  if (ranking === 2) return "info"; // 银色
  if (ranking === 3) return "success"; // 铜色
  return "";
};

// 获取奖项类型
const getPrizeType = (ranking: number) => {
  if (ranking === 1) return "warning";
  if (ranking === 2) return "info";
  if (ranking === 3) return "success";
  return "";
};

// 查看队伍详情
const viewTeamDetail = (team: any) => {
  ElMessage.info(`查看队伍详情：${team.teamName}`);
};

// 查看比赛记录
const viewMatchHistory = (team: any) => {
  ElMessage.info(`查看比赛记录：${team.teamName}`);
};

// 导出结果
const exportResults = () => {
  ElMessage.success("导出成功");
};

// 生成证书
const generateCertificate = () => {
  ElMessage.success("证书生成成功");
};

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return;

  const chart = echarts.init(chartContainer.value);

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: ["0-20", "21-40", "41-60", "61-80", "81-100", "100+"],
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: "value",
      name: "队伍数量"
    },
    series: [
      {
        name: "得分分布",
        type: "bar",
        data: [1, 3, 5, 4, 2, 1],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#409eff" },
            { offset: 1, color: "#79bbff" }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#337ecc" },
              { offset: 1, color: "#6ba3d6" }
            ])
          }
        }
      }
    ]
  };

  chart.setOption(option);

  // 响应式调整
  window.addEventListener("resize", () => {
    chart.resize();
  });
};

// 加载比赛结果
const loadMatchResults = async () => {
  const matchId = route.params.id;
  // 这里应该根据ID调用API获取比赛结果
  console.log("加载比赛结果:", matchId);
};

onMounted(async () => {
  await loadMatchResults();
  await nextTick();
  initChart();
});
</script>

<style scoped lang="scss">
.match-result-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.match-header-card {
  margin-bottom: 20px;

  .match-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .match-info {
      flex: 1;

      .match-title {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 8px 0;
      }

      .match-subtitle {
        font-size: 16px;
        color: #606266;
        margin: 0 0 12px 0;
      }

      .match-meta {
        display: flex;
        align-items: center;
        gap: 16px;

        .match-time {
          color: #909399;
          font-size: 14px;
        }
      }
    }

    .actions {
      display: flex;
      gap: 8px;
    }
  }
}

.podium-card {
  margin-bottom: 20px;

  .podium-container {
    display: flex;
    justify-content: center;
    padding: 20px 0;

    .podium {
      display: flex;
      align-items: flex-end;
      gap: 20px;

      .podium-item {
        text-align: center;
        position: relative;

        .podium-position {
          position: absolute;
          top: -10px;
          left: 50%;
          transform: translateX(-50%);
          width: 30px;
          height: 30px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
          font-size: 16px;
          color: white;
        }

        .podium-content {
          padding: 30px 20px 20px;
          border-radius: 8px;
          min-width: 150px;

          .team-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 12px;
            font-size: 24px;
            color: white;

            &.champion {
              background: linear-gradient(135deg, #ffd700, #ffed4e);
              color: #333;
            }
          }

          .team-name {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
            margin-bottom: 8px;
          }

          .team-score {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 8px;
          }

          .prize-info {
            font-size: 12px;
            color: #606266;
          }
        }

        &.rank-1 {
          .podium-position {
            background: linear-gradient(135deg, #ffd700, #ffed4e);
            color: #333;
          }

          .podium-content {
            background: linear-gradient(135deg, #ffd700, #ffed4e);
            height: 200px;

            .team-score {
              color: #333;
            }
          }
        }

        &.rank-2 {
          .podium-position {
            background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
            color: #333;
          }

          .podium-content {
            background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
            height: 160px;

            .team-avatar {
              background: linear-gradient(135deg, #909399, #b1b3b8);
            }

            .team-score {
              color: #333;
            }
          }
        }

        &.rank-3 {
          .podium-position {
            background: linear-gradient(135deg, #cd7f32, #daa520);
          }

          .podium-content {
            background: linear-gradient(135deg, #cd7f32, #daa520);
            height: 120px;

            .team-avatar {
              background: linear-gradient(135deg, #b8860b, #cd853f);
            }

            .team-score {
              color: white;
            }
          }
        }
      }
    }
  }
}

.ranking-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .filters {
      display: flex;
      gap: 12px;
    }
  }

  .ranking-cell {
    .ranking-number {
      font-weight: 600;
      color: #303133;
    }
  }

  .team-cell {
    display: flex;
    align-items: center;
    gap: 8px;

    .team-avatar-small {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background-color: #f0f2f5;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #909399;
    }

    .team-name {
      font-weight: 500;
    }
  }

  .score-text {
    font-weight: 600;
    color: #409eff;
  }

  .win-text {
    color: #67c23a;
    font-weight: 600;
  }

  .loss-text {
    color: #f56c6c;
    font-weight: 600;
  }

  .win-rate {
    font-weight: 600;
  }

  .avg-score {
    font-weight: 500;
  }

  .no-prize {
    color: #c0c4cc;
  }
}

.stats-card,
.chart-card {
  margin-bottom: 20px;

  .title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.stats-content {
  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f2f5;

    &:last-child {
      border-bottom: none;
    }

    .stat-label {
      color: #606266;
      font-size: 14px;
    }

    .stat-value {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.chart-container {
  height: 300px;
  width: 100%;
}

.highlights-card {
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.highlights-content {
  .highlight-item {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    padding: 16px 0;
    border-bottom: 1px solid #f0f2f5;

    &:last-child {
      border-bottom: none;
    }

    .highlight-time {
      flex-shrink: 0;
      font-size: 12px;
      color: #909399;
      width: 120px;
    }

    .highlight-content {
      flex: 1;

      .highlight-title {
        font-weight: 600;
        color: #303133;
        margin-bottom: 4px;
      }

      .highlight-desc {
        color: #606266;
        font-size: 14px;
        line-height: 1.5;
      }
    }

    .highlight-score {
      flex-shrink: 0;
      font-weight: 600;
      color: #409eff;
      font-size: 14px;
    }
  }
}

@media (max-width: 768px) {
  .match-result-container {
    padding: 10px;
  }

  .match-header {
    flex-direction: column;
    gap: 16px;

    .actions {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .podium {
    flex-direction: column;
    align-items: center;

    .podium-item {
      &.rank-1,
      &.rank-2,
      &.rank-3 {
        .podium-content {
          height: auto;
          min-height: 120px;
        }
      }
    }
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;

    .filters {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .chart-container {
    height: 250px;
  }
}
</style>
